package com.base.app_core.service.rx;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.App;
import com.base.app_core.base.BaseView;
import com.base.app_core.base.impl.BasePresenter;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.Retrofit.HttpResult;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.NetworkUtils;
import com.tencent.bugly.crashreport.CrashReport;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.List;

import io.reactivex.observers.DefaultObserver;


/**
 * Created by xiangheng.song on 2017/2/28.
 */

public class Callback<T> extends DefaultObserver<HttpResult<T>> {

    private WeakReference<BaseView> target;
    private boolean bAddRequFreq = false;

    public Callback(boolean b) {
        this.bAddRequFreq = b;
    }

    public Callback() {
        bAddRequFreq = false;
    }

    public Callback<T> setTarget(BaseView target) {
        this.target = new WeakReference<BaseView>(target);
        return this;
    }


    @Override
    public void onError(Throwable e) {
        try {
            F.http(e.getMessage());
            String errmsg;
            if (!NetworkUtils.isAvailableByPing()) {
                errmsg = "你连接的网络有问题，请检查路由器";
            } else {
                errmsg = "服务器解析异常";
            }
            if (target != null && target.get() != null) {
                target.get().notifyError("500", errmsg);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            CrashReport.postCatchedException(e);
        }
    }

    @Override
    public void onComplete() {

    }


    @Override
    public void onNext(HttpResult<T> httpResult) {
        try {
            T data = httpResult.getData();
            Object exteraData=httpResult.getExteraData();
            // 如果服务端要求登录,则弹出登录页面
            String errorCode = httpResult.getErrorCode();
            if (AppConstants.ERROR_CODE.NEED_LOGIN.equals(errorCode) || "1085".equals(errorCode)) {
                AppConstants.Const.NeedLogin = true;
                App.lastCallback = target.get();
                Preferences.putString(AppConstants.SP.JWTOKEN, null);
                ARouter.getInstance().build(AppConstants.ROUTEURI.LOGIN).navigation();
                return;
                // 系统繁忙不处理
            } else if (AppConstants.ERROR_CODE.SYSTEM_BUSY.equals(errorCode)) {
                return;
            }

            if (httpResult.isXybsuccess()) {
                F.j("onRespond");
                onResponse(httpResult.getData(), httpResult.getPaginated(),exteraData);
            } else {
                F.j("onFailed");
                onFailed(httpResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
        }

    }

    //mvv
    public void onFailed(HttpResult<T> data) {
        if (target != null && target.get() != null) {
            target.get().notifyError(data.getErrorCode(), data.getMsg());
        }
    }

    public void onResponse(T data, Paginated paginated,Object extraData) {
        try {
            if (bAddRequFreq && mPressenter != null && null != mPressenter.get())
                mPressenter.get().addReqFinish();

            if (target != null && target.get() != null) {
                if (data != null && data instanceof Collection) {
                    List datalst = (List) data;
                    Class cla = null;
                    if (datalst.size() != 0)
                        cla = datalst.get(0).getClass();
                    target.get().notifyData(data, cla, paginated);
                } else {
                    target.get().notifyData(data, null, paginated);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
        }
    }

    private WeakReference<BasePresenter> mPressenter = null;

    public <T extends BaseView> void setPressenter(BasePresenter<T> tBasePresenter) {
        mPressenter = new WeakReference<BasePresenter>(tBasePresenter);
    }
}
